package top.withwings.bonus.bonus.pojo.bonus.rule;

import top.withwings.bonus.bonus.pojo.BonusForm;
import top.withwings.bonus.bonus.pojo.Rate;

import java.util.Date;
import java.util.LinkedHashMap;

public class ExpirationCloseBonusRule extends SingleBonusRule{
    public static final String TYPE = "EXPIRATION-CLOSE";


    public ExpirationCloseBonusRule(int id, String name, LinkedHashMap<String, Double> paramMap) {
        super(id, name, paramMap);
        this.type = TYPE;
    }


    @Override
    public Rate applyOn(BonusForm bonusForm) {
        if(bonusForm.getExpiration() == null){
            return Rate.NOT_APPLIED;
        }

        double x1 = this.paramMap.get("x1");
        double y1 = this.paramMap.get("y1");

        double x2 = this.paramMap.get("x2");
        double y2 = this.paramMap.get("y2");

        double x3 = this.paramMap.get("x3");
        double y3 = this.paramMap.get("y3");

        long daysBeforeExpiry = getDaysBeforeExpiry(bonusForm.getEffectiveDate(),bonusForm.getExpiration());

        if(daysBeforeExpiry  <= x1){
            return new Rate(Rate.TYPE_NORMAL,y1);
        }else if(daysBeforeExpiry <= x2){
            return new Rate(Rate.TYPE_NORMAL,y2);
        }else if(daysBeforeExpiry <= x3){
            return new Rate(Rate.TYPE_NORMAL,y3);
        }else{
            return Rate.NOT_APPLIED;
        }


    }

    private long getDaysBeforeExpiry(Date effectiveDate, Date expiration) {

        return  (expiration.getTime() - effectiveDate.getTime())/( 24*60*60*1000L);

    }


    @Override
    public void check(){
        double x1 = this.paramMap.get("x1");
        double x2 = this.paramMap.get("x2");
        double x3 = this.paramMap.get("x3");

        if(x1<x2 && x2<x3){
            //OK
        }else{
            throw new IllegalArgumentException("天数必须逐级增加");
        }

    }

}

